package com.alongthink.javademo.utilTools;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Tools {

    /**
     * 两个类实例之间变量的赋值
     * @param ojb 源
     * @param cls 目标类
     * @param <T>
     * @return
     */
    public static <T> T toMapperClass(Object ojb,Class<T> cls){
        return JSON.parseObject(JSON.toJSONString(ojb),cls);
    }

    /**
     * 获取本机IP地址
     * @return
     */
    public static String getLocalIp(){
        String ip = "127.0.0.1";
        try {
            InetAddress ip4 = Inet4Address.getLocalHost();
            ip = ip4.getHostAddress();
        }catch (Exception ex){

        }
        return ip;
    }


    //获取客户端IP地址
    public static String getIpAddr(HttpServletRequest request) {
        System.out.println(request);
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress)) {
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            // "***.***.***.***".length()
            if (ipAddress != null && ipAddress.length() > 15) {
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }


    //反转数组
    public static char[] ReverseArray(char[] arr){
        for (int i = 0; i < arr.length/2; i++) {//这里除以二是防止再次判断.如果不除2,还是会将换过来的元素再换回去
            //if (arr[i]<arr[arr.length-i-1]) {//
//-i-1,第一个和最后一个交换就是arr[0]和arr[6-0-1]
//第二个和倒数第二个交换就是arr[1]和arr[6-1-1];以此类推
                char temp=arr[arr.length-i-1];
                arr[arr.length-i-1]=arr[i];
                arr[i]=temp;
            //}
        }
        return arr;
    }

}
